<template>
  <Card
    title="故障信息"
    :bordered="false"
    :loading="loading"
    class="chaos-card"
  >
    <div v-if="injectedChaos">
      <FormItem
        label="已注入故障："
        name="instance"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <span>{{ injectedChaos.params[0].value }}</span>
      </FormItem>
      <FormItem
        label="注入故障类型："
        name="instance"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <span>{{ injectedChaos.describe }}</span>
        <template #extra v-if="selectedChaosNote">
          <span style="color: #faad14;font-size:12px">{{ selectedChaosNote }}</span>
        </template>
      </FormItem>
      <FormItem
        label="故障状态："
        name="instance"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <span>{{ getInstanceStatusDescribe(injectedChaos.status) }}</span>
      </FormItem>
      <FormItem :wrapper-col="{ offset: 6, span: 18 }">
        <Button type="primary" @click="stopChaos">解除故障</Button>
      </FormItem>
    </div>
    <Form
      v-else
      :model="formState"
      name="basic"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      autocomplete="off"
      @finish="onSubmit"
    >
      <FormItem
        label="故障点"
        name="instance"
        :rules="[{ required: true, message: '请选择需要注入故障的节点' }]"
      >
        <span v-if="!instance || instance.length == 0" style="color: #bfbfbf"
          >请点击左侧拓扑图，选择节点</span
        >
        <span v-else>{{ instance }}</span>
      </FormItem>
      <FormItem
        label="故障类型"
        name="selectedChaosName"
        :rules="[{ required: true, message: '请选择故障类型' }]"
      >
        <Select
          v-model:value="selectedChaosName"
          style="width: 200px"
          :options="chaosList"
          @change="changeChaos"
          :field-names="{ label: 'describe', value: 'complex_action' }"
          placeholder="请选择故障类型"
        ></Select>

        <template #help v-if="selectedChaosNote">
          <span style="color: #faad14;font-size:12px">{{ selectedChaosNote }}</span>
        </template>
      </FormItem>
      <FormItem :wrapper-col="{ offset: 6, span: 18 }">
        <Button html-type="submit" type="primary">注入故障</Button>
      </FormItem>
    </Form>
  </Card>
</template>

<script lang="ts">
import { Select, Form, Button, Card, notification } from "ant-design-vue";
import { defineComponent, reactive, ref, onMounted, watch, toRefs } from "vue";
import eventBus from "../../../utils/eventBus";
import { getScenceChaosListApi } from "@/api/scence/index";
import {
  createChaosApi,
  getChaosListApi,
  getChaosStatusApi,
  stopChaosApi,
} from "@/api/chaos/index";
import axios from "axios";
import { useInstanceModuleStore } from "@/store/instance";
import { mapState } from "pinia";
export default defineComponent({
  components: {
    Form,
    FormItem: Form.Item,
    Select,
    Button,
    Card,
  },
  setup() {
    const chaosList = ref<any[]>([]);
    const injectedChaos = ref<any>({});
    const formState = reactive({
      selectedChaosName: "",
      instance: "",
    });
    const selectedChaos = ref<any>({});
    const selectedChaosNote = ref<string>("");
    const loading = ref<boolean>(true);
    const stopChaosAction = ref<boolean>(false);

    // 监听事件
    onMounted(() => {
      eventBus.on("click-instance", (data) => {
        formState.instance = data;
        getScenceChaosList();
        // chaosList.value = []
      });
      eventBus.on("change-request", (data) => {
        // selectedChaosName.value = null;
        // instance.value = null;
        // injectedChaos.value = null;
        // selectedChaos.value = null;
      });
    });

    const getScenceChaosList = () => {
      getScenceChaosListApi(formState.instance).then((res: any) => {
        if (res.code === "0") {
          chaosList.value = res.data.chaos_list;
          if (
            !chaosList.value.find(
              (item) =>
                item.complex_action === selectedChaos.value.complex_action &&
                item.describe === selectedChaos.value.describe &&
                item.note === selectedChaos.value.note
            )
          ) {
            formState.selectedChaosName = "";
            selectedChaos.value = "";
            selectedChaosNote.value = "";
          }
        }
      });
    };

    const getChaosStatus = () => {
      getChaosStatusApi()
        .then((res: any) => {
          if (res.code === "0") {
            injectedChaos.value = res.data.chaos;
            selectedChaosNote.value = res.data.chaos?.note;
          }
        })
        .finally(() => {
          loading.value = false;
        });
    };

    getChaosStatus();
    getScenceChaosList();

    const instanceStore = useInstanceModuleStore();

    watch(
      () => instanceStore.getInstance,
      (newInstance, oldInstance) => {
        if (!newInstance && oldInstance) {
          loading.value = false;
          if (stopChaosAction.value) {
            notification["success"]({
              message: "解除故障成功",
            });
          }
        }
        injectedChaos.value = newInstance;
        console.log(newInstance);
        if (newInstance) {
          selectedChaosNote.value = newInstance.note;
        } else {
          selectedChaosNote.value = selectedChaos.value.note;
        }
      }
    );
    return {
      chaosList,
      formState,
      ...toRefs(formState),
      selectedChaos,
      injectedChaos,
      loading,
      getChaosStatus,
      stopChaosAction,
      selectedChaosNote,
    };
  },
  methods: {
    changeChaos(value, option) {
      this.selectedChaos = option;
      this.selectedChaosNote = option.note;
    },
    onSubmit() {
      if (!this.instance) {
        notification["error"]({
          message: "请选择需要注入故障的节点",
        });
      } else {
        this.loading = true;
        createChaosApi({
          complex_action: this.selectedChaos.complex_action,
          params: [
            {
              name: "instance",
              type: "string",
              value: this.instance,
            },
          ],
          describe: this.selectedChaos.describe,
        })
          .then((res) => {
            if (res.code === "0") {
              this.injectedChaos = res.data.chaos_list;
              this.selectedChaosNote = res.data.chaos_list?.note;
              this.loading = false;

              eventBus.emit("after-inject", this.injectedChaos);
            }
          })
          .catch((err) => {
            notification["error"]({
              message: "故障注入失败",
            });
            this.loading = false;
          })
          .finally(() => {});
      }
    },
    onClickInstance() {},
    stopChaos() {
      this.loading = true;
      stopChaosApi()
        .then((res) => {
          if (res.code === "0") {
            this.stopChaosAction = true;
          }
        })
        .finally(() => {});
    },
    getInstanceStatusDescribe(status: string) {
      switch (status) {
        case "injectFailed":
          return "故障注入失败";
          break;
        case "running":
          return "正常运行中";
          break;
        case "injecting":
          return "故障注入中";
          break;
        case "injected":
          return "已经完成故障注入";
          break;
      }
    },
  },
});
</script>

<style lang="less" scoped>
.chaos-card {
  :deep(.ant-card-body) {
    padding: 20px
  }
  :deep(.ant-form-item) {
    margin-bottom: 12px
  }
}
</style>